package com.chushouya.product.service.api.impl;

import com.chushouya.common.support.RequestUserContext;
import com.general.framework.core.enums.StatusEnum;
import com.general.framework.core.lang.Longs;
import com.chushouya.product.dao.entity.EvaluateLogEntity;
import com.chushouya.product.dao.entity.ProductEntity;
import com.chushouya.product.dao.entity.VisitDeviceEntity;
import com.chushouya.product.dao.repository.EvaluateLogRepository;
import com.chushouya.product.dao.repository.ProductRepository;
import com.chushouya.product.dao.repository.VisitDeviceRepository;
import com.chushouya.product.dto.api.evaluate.VisitDeviceApiDTO;
import com.chushouya.product.dto.api.evaluate.VisitDeviceRequestApiDTO;
import com.chushouya.product.dto.api.visitdevice.VisitDeviceQuery;
import com.chushouya.product.service.api.VisitDeviceApiService;
import com.general.framework.core.lang.Strings;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.Date;
import java.util.Objects;

/**
 * 获取本机机型API服务实现类
 * 
 * @author chushouya
 */
@Service
@Slf4j
public class VisitDeviceApiServiceImpl implements VisitDeviceApiService {

    @Resource
    private EvaluateLogRepository evaluateLogRepository;
    
    @Resource
    private VisitDeviceRepository visitDeviceRepository;
    
    @Resource
    private ProductRepository productRepository;

    @Override
    public VisitDeviceApiDTO visitDevice(VisitDeviceRequestApiDTO request) {
        log.info("获取本机机型信息，品牌：{}，机型：{}，系统：{}",
                request.getDeviceBrand(),
                request.getDeviceName(),
                request.getDeviceSystem());
        
        VisitDeviceApiDTO response = new VisitDeviceApiDTO();
        
        // 优先级三层逻辑：最近 -> 本机 -> 热门
        VisitDeviceApiDTO result = tryGetRecentEvaluateProduct(response,request);
        if (Objects.nonNull(result)) {
            return result;
        }
        
        result = tryGetDeviceMatchProduct(request, response);
        if (Objects.nonNull(result)) {
            return result;
        }
        
        return getDefaultHotProduct(response);
    }
    
    /**
     * 尝试获取用户最近的评估产品（第一层：最近）
     *
     * @param response 响应对象
     * @param request
     * @return 如果找到则返回响应，否则返回null
     */
    private VisitDeviceApiDTO tryGetRecentEvaluateProduct(VisitDeviceApiDTO response, VisitDeviceRequestApiDTO request) {
        final Long userId = request.getUserId();
        if (Longs.isNullOrZero(userId)) {
            log.debug("用户ID为空，无法查询最近评估记录");
            return null;
        }
        try {
            EvaluateLogEntity latestLog = evaluateLogRepository.selectLatestByUserId(userId);
            if (Objects.isNull(latestLog)) {
                log.debug("用户{}没有评估记录", userId);
                return null;
            }

            log.info("找到用户{}的最新评估记录，产品ID：{}", userId, latestLog.getProductId());

            response.setFromText("最近");
            response.setProductId(latestLog.getProductId());
            response.setProductName(latestLog.getProductName());
            response.setProductImage(latestLog.getProductImage());
            response.setEvaluatePrice(latestLog.getEvaluatePrice());

            return response;
        } catch (Exception e) {
            // 只捕获数据库查询相关异常
            log.warn("查询用户评估记录时发生异常", e);
            return null;
        }
    }
    
    /**
     * 检查用户上下文是否为空对象（未登录状态）
     */
    private boolean isEmptyUserContext(RequestUserContext userContext) {
        return userContext.getUserId() == null && 
               userContext.getUserName() == null && 
               userContext.getUserType() == null;
    }
    
    /**
     * 尝试获取设备匹配的产品（第二层：本机）
     * 
     * @param request 请求对象
     * @param response 响应对象
     * @return 如果找到则返回响应，否则返回null
     */
    private VisitDeviceApiDTO tryGetDeviceMatchProduct(VisitDeviceRequestApiDTO request, VisitDeviceApiDTO response) {
        try {
            VisitDeviceEntity deviceMatch = findMatchingDevice(request);
            if (Objects.isNull(deviceMatch)) {
                return null;
            }
            
            Long productId = deviceMatch.getProductId();
            if (!Longs.notNullAndZero(productId)) {
                return null;
            }
            
            ProductEntity product = getProductInfo(productId);
            if (Objects.isNull(product)) {
                return null;
            }
            
            log.info("找到匹配的设备记录，设备：{}，产品ID：{}", deviceMatch.getDeviceName(), productId);
            
            response.setFromText("本机");
            response.setProductId(product.getProductId());
            response.setProductName(product.getProductName());
            response.setProductImage(product.getProductImage());
            response.setEvaluatePrice(product.getMaxPrice());
            
            // 更新访问次数
            visitDeviceRepository.incrementVisitCount(deviceMatch.getDeviceId());
            
            return response;
        } catch (Exception e) {
            log.warn("获取设备匹配产品失败，设备名称：{}", request.getDeviceName(), e);
            return null;
        }
    }
    
    /**
     * 获取默认热门产品（第三层：热门）
     * 
     * @param response 响应对象
     * @return 返回默认产品响应
     */
    private VisitDeviceApiDTO getDefaultHotProduct(VisitDeviceApiDTO response) {
        try {
            ProductEntity defaultProduct = productRepository.selectByPrimaryKey(100001L);
            if (Objects.nonNull(defaultProduct)) {
                log.info("使用默认热门产品，产品ID：100001");
                
                response.setFromText("热门");
                response.setProductId(defaultProduct.getProductId());
                response.setProductName(defaultProduct.getProductName());
                response.setProductImage(defaultProduct.getProductImage());
                response.setEvaluatePrice(defaultProduct.getMaxPrice());
            } else {
                log.warn("默认产品100001不存在，返回空响应");
            }
            
            return response;
        } catch (Exception e) {
            log.error("获取默认热门产品失败", e);
            return response;
        }
    }
    
    /**
     * 查找匹配的设备记录
     * 
     * @param request 设备请求信息
     * @return 匹配的设备实体
     */
    private VisitDeviceEntity findMatchingDevice(VisitDeviceRequestApiDTO request) {
        if (Strings.isEmpty(request.getDeviceName())) {
            return null;
        }
        
        VisitDeviceQuery query = new VisitDeviceQuery();
        query.setDeviceName(request.getDeviceName());
        query.setStatus(StatusEnum.normal.value());
        
        // 尝试精确匹配设备名称
        VisitDeviceEntity existingDevice = visitDeviceRepository.selectOne(query);
        if (Objects.nonNull(existingDevice)) {
            return existingDevice;
        }
        
        // 如果没有找到匹配记录，插入新设备记录
        return insertNewDeviceRecord(request);
    }
    
    /**
     * 插入新的设备记录
     * 
     * @param request 设备请求信息
     * @return 新插入的设备实体
     */
    private VisitDeviceEntity insertNewDeviceRecord(VisitDeviceRequestApiDTO request) {
        try {
            VisitDeviceEntity newDevice = new VisitDeviceEntity();
            newDevice.setDeviceName(request.getDeviceName());
            newDevice.setDeviceBrand(request.getDeviceBrand());
            newDevice.setDeviceSystem(request.getDeviceSystem());
            
            // 设置默认值
            newDevice.setStatus(StatusEnum.normal.value());
//            newDevice.setPlatform("miniprogram"); // 小程序平台
            newDevice.setVisitCount(1); // 初始访问次数为1
            newDevice.setCreatedAt(new Date());
            newDevice.setUpdatedAt(new Date());
            // 插入数据库
            visitDeviceRepository.insertSelective(newDevice);
            log.info("插入新设备记录成功，设备名称：{}，设备ID：{}", request.getDeviceName(), newDevice.getDeviceId());
            
            return newDevice;
        } catch (Exception e) {
            log.error("插入新设备记录失败，设备名称：{}", request.getDeviceName(), e);
            return null;
        }
    }

    /**
     * 获取产品信息
     * 
     * @param productId 产品ID
     * @return 产品实体
     */
    private ProductEntity getProductInfo(Long productId) {
        if (Longs.notNullAndZero(productId)) {
            return productRepository.selectByPrimaryKey(productId);
        }
        return null;
    }
}
